package com.sunny.controller;

/**
 * @ClassName:
 * @Description:
 * @author: yubao.jin
 * @date: 2018/5/13
 * @version:V1.0
 */

import com.sunny.common.Const;
import com.sunny.pojo.User;
import com.sunny.service.IUserService;
import com.sunny.utils.PageInformation;
import com.sunny.utils.PageUtil;
import com.sunny.utils.ResponseCode;
import com.sunny.utils.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by JinDaShuai on 2018/1/22.
 */
@Controller
@RequestMapping("/user/")
public class UserController {
    @Autowired
    private IUserService iUserService;

    /**
     * 用户登陆
     * @param : name
     * @param password
     * @param session
     * @return
     */
    @RequestMapping(value = "login.do")
    @ResponseBody
    public ModelAndView login(String name, String password, HttpSession session) {
        ServerResponse<User> response = iUserService.login(name, password);
        ModelAndView modelAndView = new ModelAndView();

        if(response.isSuccess()) {
            User user = response.getData();
            Integer roleNo = user.getRoleNo();
            if(roleNo == Const.Role.ROLE_SELLER) {
                if(user.getEffect() != 1) {
                    modelAndView.addObject("您的账号还未生效");
                }
            }
            switch (roleNo)
            {
                case Const.Role.ROLE_BUYER : modelAndView.setViewName("/buyer/buyer"); break;
                case Const.Role.ROLE_SELLER : modelAndView.setViewName("/seller/seller"); break;
                case Const.Role.ROLE_ADMIN : modelAndView.setViewName("/admin/admin"); break;
                default: modelAndView.setViewName("login"); break;
            }
            session.setAttribute(Const.CURRENT_USER, response.getData());
        } else {
            modelAndView.setViewName("login");
        }

        return  modelAndView;
    }

    @RequestMapping(value = "logout.do")
    @ResponseBody
    public ModelAndView logout( HttpSession session) {
        session.removeAttribute(Const.CURRENT_USER);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login");
        return modelAndView;
    }

    @RequestMapping(value = "register.do")
    @ResponseBody
    public ServerResponse<String> register(User user) {
        return iUserService.register(user);
    }

    @RequestMapping(value = "check_valid.do")
    @ResponseBody
    public ServerResponse<String> checkValid(String str, String type) {
        return iUserService.checkValid(str, type);
    }

    @RequestMapping(value = "get_user_info.do")
    @ResponseBody
    public ServerResponse<User> getUserInfo(HttpSession session) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(user != null) {
            return ServerResponse.createBySuccess(user);
        }

        return ServerResponse.createByErrorMessage("用户未登陆，无法获取当前用户信息");
    }

    @RequestMapping(value = "forget_get_question.do")
    @ResponseBody
    public  ServerResponse<String> forgetGetQuestion(String username) {
        return iUserService.selectQuestion(username);
    }

    @RequestMapping(value = "forget_check_answer.do")
    @ResponseBody
    public ServerResponse<String> forgetCheckAnswer(String username, String question, String answer) {
        return iUserService.checkAnswer(username, question, answer);
    }

    @RequestMapping(value = "forget_reset_password.do")
    @ResponseBody
    public ServerResponse<String> forgetRestPassword(String username, String passwordNew, String forgetToken) {
        return iUserService.forgetResetPassword(username, passwordNew, forgetToken);
    }

    @RequestMapping(value = "reset_password.do")
    @ResponseBody
    public ServerResponse<String> resetPassword(HttpSession session, String passwordOld, String passwordNew) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(user == null) {
            return ServerResponse.createByErrorMessage("用戶未登陸");
        }

        return iUserService.resetPassword(passwordOld, passwordNew, user);
    }

    @RequestMapping(value = "update_information.do")
    @ResponseBody
    // 更新用戶個人信息：在更新完信息之後，需要把新的用戶信息放到session,同時把新的用戶信息返回到前端
    public ServerResponse<User> update_information(HttpSession session, User user) {
        User currentUser = (User)session.getAttribute(Const.CURRENT_USER);
        if(currentUser == null) {
            return ServerResponse.createByErrorMessage("用戶未登陸");
        }

        // 跟新用戶信息，并且把一些信息放到其中
        user.setId(currentUser.getId()); // 防止橫向越權
        user.setName(currentUser.getName()); // 雖然不更新username,但是始終要把username放入session中
        ServerResponse<User> response = iUserService.updateInformation(user);
        if(response.isSuccess()) {
            session.setAttribute(Const.CURRENT_USER, response.getData());
        }

        return response;
    }

    @RequestMapping(value = "get_information.do")
    @ResponseBody
    public ServerResponse<User> getInformation(HttpSession session) {
        User currentUser = (User)session.getAttribute(Const.CURRENT_USER);
        if(currentUser == null) {
            // 使其强制登陸
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "未登陸需要强制登陸status=10");
        }

        return iUserService.getInformation(currentUser.getId());
    }

    @RequestMapping(value = "list.do")
    @ResponseBody
    public PageInformation<User> list(HttpServletRequest request, HttpSession session, User user) {
        if(user != null) {
            if(user.getRoleNo() == 7) {
                user.setRoleNo(null);
            }
        }

        String pageNumber = request.getParameter("offset");
        String pageSize = request.getParameter("limit");
        PageUtil pageUtil = PageUtil.getInstance();
        pageUtil.setPageNum(Integer.parseInt(pageNumber) / Integer.parseInt(pageSize) + 1);
        pageUtil.setPageSize(Integer.parseInt(pageSize));

        return iUserService.list(pageUtil, user);
    }

    @RequestMapping("del.do")
    @ResponseBody
    public ServerResponse del(@RequestParam(value = "arr", required = false) String[] id) {
        return iUserService.del(id);
    }
}
